package net.xdclass.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.OssConfig;
import net.xdclass.controller.request.AccountRegisterRequest;
import net.xdclass.service.FileService;
import net.xdclass.utils.CommonUtil;
import net.xdclass.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

     @Autowired
     private  OssConfig ossConfig;
    @Override
    public String uploadUserImg(MultipartFile file) {
        String bucketName = ossConfig.getBucketName();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //思考怎么与阿里云通讯 OSS客户端构建
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取原始名称  xxx.jpg
        String originalFilename = file.getOriginalFilename();

        //jdk8获取日期格式化
        LocalDateTime ldt = LocalDateTime.now();
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy/MM/dd/");
        //user/2022/12/12/asdas/
        //获取文件夹
        String folder = pattern.format(ldt);

        String fileName = CommonUtil.generateUUID();
        //扩展名
        String extendsion = originalFilename.substring(originalFilename.lastIndexOf('.'));
        //在oss上的bucket创建文件夹
        String newFileName = "user/" + folder + "/" + fileName  + extendsion;
        try {
            //文件上传
            PutObjectResult putObjectResult = oss.putObject(bucketName, newFileName, file.getInputStream());
            //拼装返回路径
            if (putObjectResult != null) {
                String imgUrl = "https://" + bucketName + "." + endpoint + "/" + newFileName;
                return imgUrl;
            }
        } catch (IOException e) {
            log.error("文件上传失败:{}",e.getMessage());
        }finally {
            oss.shutdown();
        }
        return null;
    }


}
